import authCache from "@/utils/cache/authCache.js";
import common from "@/base/common.js";
const AuthenticationScheme = "Bearer";
const ResultCodeEnum = {
  SUCCESS: 0,
  SUCCESS200: 200,
  ACCOUNT_PWD_ERR: 40006,
  SYSTEM_BUSY: -1,
  BASE_VALID_PARAM: -9,
  JWT_PASSWORD_INVALID: 40010,
  UNAUTHORIZED: 401,
  JWT_PARSER_TOKEN_FAIL: 40005,
  JWT_NOT_LOGIN: 40009,
  JWT_TOKEN_EXPIRED: 40001,
};
const HttpStatusEnum = {
  SUCCESS: 200,
  UNAUTHORIZED: 401,
};
const RequestMethodEnum = {
  GET: "GET",
  POST: "POST",
  PUT: "PUT",
  DELETE: "DELETE",
};
const ContentTypeEnum = {
  // json
  JSON: "application/json;charset=UTF-8",
  // form-data qs
  FORM_URLENCODED: "application/x-www-form-urlencoded;charset=UTF-8",
  // form-data  upload
  FORM_DATA: "multipart/form-data;charset=UTF-8",
};
function dealErrorResponse(response) {
  return (
    response.data || {
      code: response.statusCode,
      msg: response.statusText,
    }
  );
}
function hideLoading() {
  uni.hideLoading();
}
/*
	config: uni.request的config对象
	options: 自定义额外配置选项，具体如下
*/
function doReq(config, options) {
  options = Object.assign(
    {
			//默认的请求失败处理
      useDefaultFailHandle: true,
			//默认的请求错误处理
      useDefaultErrHandle: true,
      //是否带token
			withToken: true,
			//是否有uni.showLoading的全局加载效果
      useGlobalLoading: true,
			//是否自动加上common.baseUrl的域名
			autoPrefixBaseUrl: true
    },
    options || {}
  );
  if (!config.header) {
    config.header = {};
  }
  config.header["Content-Type"] = ContentTypeEnum.JSON;
  if (options.withToken) {
    const token = authCache.getToken();
    if (token) {
      config.header.Authorization = `${AuthenticationScheme} ${token}`;
    } else {
      uni.redirectTo({
        url: "/pages/login/login",
      });
      return Promise.reject(null);
    }
  }
  if (options.useGlobalLoading) {
    uni.showLoading({
      title: "加载中...",
      mask: true,
    });
  }
	if(options.autoPrefixBaseUrl){
		config.url = common.baseUrl + config.url;
	}
	console.log("发送请求",config.url,config.data);
  return new Promise((resolve, reject) => {
    config.fail = (response) => {
			console.log("请求失败",config.url,response);
      const data = response
        ? dealErrorResponse(response)
        : {
            msg: null,
            code: null,
          };
      if (options.useDefaultErrHandle) {
        //默认异常处理
        uni.showToast({
          icon: "error",
          title: data.msg || "加载失败了",
        });
        resolve(null);
        if (data.code === ResultCodeEnum.JWT_NOT_LOGIN || data.code === ResultCodeEnum.JWT_TOKEN_EXPIRED) {
          uni.redirectTo({
            url: "/pages/login/login",
          });
        }
      } else {
        //自定义异常处理
        reject(data);
      }
    };
    config.success = (response) => {
			console.log("请求成功",config.url,response);
      if (response.statusCode === HttpStatusEnum.SUCCESS) {
        const data = response.data;
        if (data) {
          if (data.code === ResultCodeEnum.SUCCESS || data.code === ResultCodeEnum.SUCCESS200) {
            resolve(data.data ? data.data : data);
          } else if (data.code === ResultCodeEnum.UNAUTHORIZED || data.code === ResultCodeEnum.JWT_NOT_LOGIN) {
            //token过期或未登录
            uni.redirectTo({
              url: "/pages/login/login",
            });
            resolve(null);
            if (data.code === ResultCodeEnum.JWT_NOT_LOGIN) {
              uni.showToast({
                icon: "error",
                title: data.msg || "登录过期",
              });
            }
          } else {
            if (options.useDefaultFailHandle) {
              uni.showToast({
                icon: "error",
                title: data.msg || "加载失败了",
              });
              resolve(null);
            } else {
              reject(data);
            }
          }
          return;
        }
      }
      reject({
        code: response.statusCode,
        msg: response.statusText,
      });
    };
    config.complete = () => {
      hideLoading();
    };
    uni.request(config);
  });
}
const req = {
  get(config, options) {
    config.method = RequestMethodEnum.GET;
    return doReq(config, options);
  },
  post(config, options) {
    config.method = RequestMethodEnum.POST;
    return doReq(config, options);
  },
  delete(config, options) {
    config.method = RequestMethodEnum.DELETE;
    return doReq(config, options);
  },
  put(config, options) {
    config.method = RequestMethodEnum.PUT;
    return doReq(config, options);
  },
};
export default req;
